<template>
  <div class="app-container home">
    <!-- 搜索区域 - 修改为开课管理搜索项 -->
    <el-form :model="searchForm" class="search-form">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="课程名称">
            <el-input v-model="searchForm.courseName" placeholder="请输入课程名称" />
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态" style="width: 100%">
              <el-option label="未开课" value="未开课" />
              <el-option label="已开课" value="已开课" />
              <el-option label="已结束" value="已结束" />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <div class="search-actions" style="margin-top: 24px;">
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </div>
        </el-col>
      </el-row>
    </el-form>

    <!-- 表格区域 - 修改为开课管理字段 -->
    <el-table
      ref="tableRef"
      :data="tableData"
      border
      stripe
      :row-key="row => row.id"
      @selection-change="handleSelectionChange"
    >
       <el-table-column type="selection" width="55" />
       <el-table-column prop="courseName" label="课程名称" min-width="180" />
       <el-table-column prop="courseType" label="课程类型" width="140" />
       <el-table-column prop="startTime" label="开课时间" width="160" />
       <el-table-column prop="endTime" label="结束时间" width="160" />
       <el-table-column prop="studentCount" label="学生人数" width="120" >
         <template #default="scope">
            <el-button type="link" @click="handleClassStudent(scope.row.id)">{{ scope.row.studentCount }}</el-button> 
         </template>
       </el-table-column>
       <el-table-column prop="status" label="状态" width="120">
         <template #default="scope">
           <el-tag :type="getStatusTagType(scope.row.status)">{{ scope.row.status }}</el-tag>
         </template>
       </el-table-column>
       <el-table-column label="操作" width="200" fixed="right">
         <template #default="scope">
           <el-button type="text" size="small" @click="handleEdit(scope.row)">编辑</el-button>
           <el-button type="text" size="small" @click="handleDelete(scope.row.id)">删除</el-button>
         </template>
       </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <el-pagination
      class="pagination"
      :current-page="currentPage"
      :page-size="pageSize"
      :total="total"
      @current-change="handlePageChange"
      @size-change="handleSizeChange"
      layout="prev, pager, next, jumper"
    />

    <!-- 新增批量操作栏 -->
    <div v-if="selectedRows.length > 0" class="batch-actions">
      <el-button type="danger" @click="handleBatchEdit">批量编辑</el-button>
      <el-button type="danger" @click="handleBatchDelete">批量删除</el-button>
      <el-button @click="handleCancelSelection">取消勾选</el-button>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref, getCurrentInstance } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router'
const router = useRouter()
const { proxy } = getCurrentInstance()
// 搜索表单 - 适配开课管理字段
const searchForm = reactive({
  courseName: '',
  status: ''
})

// 表格数据 - 模拟课程数据
const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const selectedRows = ref([])

// 状态标签类型映射
const getStatusTagType = (status) => {
  switch(status) {
    case '已开课': return 'success'
    case '已结束': return 'danger'
    default: return 'info'
  }
}

// 模拟课程数据
let mockData = Array.from({ length: 50 }, (_, i) => ({
  id: i + 1,
  courseName: `课程${i + 1}`,
  courseType: ['线上课程', '线下课程', '混合课程'][Math.floor(Math.random() * 3)],
  startTime: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toLocaleDateString(),
  endTime: new Date(Date.now() + Math.random() * 60 * 24 * 60 * 60 * 1000).toLocaleDateString(),
  studentCount: Math.floor(Math.random() * 100) + 10,
  status: ['未开课', '已开课', '已结束'][Math.floor(Math.random() * 3)]
}))

// 搜索方法 - 适配课程字段过滤
const handleSearch = () => {
  const filtered = mockData.filter(item => {
    const matchesCourseName = item.courseName.includes(searchForm.courseName)
    const matchesStatus = searchForm.status ? item.status === searchForm.status : true
    return matchesCourseName && matchesStatus
  })

  total.value = filtered.length
  tableData.value = filtered.slice((currentPage.value - 1) * pageSize.value, currentPage.value * pageSize.value)
}

// 重置方法
const handleReset = () => {
  searchForm.courseName = ''
  searchForm.status = ''
  currentPage.value = 1
  handleSearch()
}

// 分页变化
const handlePageChange = (page) => {
  currentPage.value = page
  handleSearch()
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  handleSearch()
}

// 选择变化
const handleSelectionChange = (rows) => {
  selectedRows.value = rows
}

// 编辑处理
const handleEdit = (row) => {
  router.push(`/classManage/edit/${row.id}`)
}

const handleBatchEdit  = () => {
  router.push({ path: '/classManage/batchEdit', query: { ids: selectedRows.value.map(row => row.id).join(',') } })
}


function handleAdd() {
  router.push({ path: '/comment/add' })
}
const handlePreview = (row) => {
  // 实际项目中这里应该跳转到预览页面
  router.push({ path: '/scoringManage/scoring', query: { id: row.id } })
}

// 删除处理
const handleDelete = (id) => {
  ElMessageBox.confirm('确定要删除该课程吗？', '确认删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    mockData = mockData.filter(item => item.id !== id)
    handleSearch()
    ElMessage({ message: '删除成功', type: 'success' })
  }).catch(() => {})
}

// 批量删除
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) return
  ElMessageBox.confirm(`确定要删除选中的${selectedRows.value.length}条课程吗？`, '确认删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const ids = selectedRows.value.map(row => row.id)
    mockData = mockData.filter(item => !ids.includes(item.id))
    selectedRows.value = []
    handleSearch()
    ElMessage({ message: '批量删除成功', type: 'success' })
  }).catch(() => {})
}

// 取消勾选
const handleCancelSelection = () => {
  selectedRows.value = []
  proxy.$refs.tableRef.clearSelection()
}

// 详情处理
const handleDetail = (row) => {
  ElMessage({ message: `查看课程详情: ${row.courseName}`, type: 'info' })
  // 实际项目中这里应该跳转到详情页面
}

// 初始化加载数据
handleSearch()

// 班级学生
const handleClassStudent = (id) => {
  router.push({ path: '/classManage/classStudent', query: { id: id } })
}

</script>

<style scoped>
/* 保持与知识点管理页面相同的样式 */
.search-form {
  margin-bottom: 20px;
  padding: 15px;
  background: #f5f7fa;
  border-radius: 4px;
}

.search-actions {
  display: flex;
  gap: 10px;
  margin-top: 22px;
}

.pagination {
  margin-top: 15px;
  text-align: right;
}

.batch-actions {
  margin-top: 10px;
  display: flex;
  gap: 10px;
}
</style>